#include "SubsystemChatLimit.h"
#include "Log.h"

namespace ChatLimit
{
    SubsystemChatLimit::SubsystemChatLimit() {}

    static const std::string subsystemName = "ChatLimit";
    const std::string& SubsystemChatLimit::getName() const
    {
        return subsystemName;
    }

    ChatLimitType SubsystemChatLimit::addMessageCount(const std::string &username)
    {
        std::lock_guard<std::mutex> lk(m_tableMutex);
        auto it = m_chatCountTable.find(username);
        if(it != m_chatCountTable.end() && it->second > 0)
        {
            it->second++;
            if(it->second > 10)
            {
                return ChatLimitType::Kick;
            }
            if(it->second > 5)
            {
                return ChatLimitType::Limit;
            }
            return ChatLimitType::Normal;
        }
        m_chatCountTable[username] = 1;
        return ChatLimitType::Normal;
    }

    void SubsystemChatLimit::update(float dt)
    {
        m_waitTime += dt;
        if(m_waitTime >= 4.5f)
        {
            m_waitTime = 0;
            bool needClear = false;
            
            std::lock_guard<std::mutex> lk(m_tableMutex);
            for(auto &pair : m_chatCountTable)
            {
                pair.second--;
                if(pair.second < -30)
                {
                    needClear = true;
                }
            }

            if(needClear == true)
            {
                std::map<std::string, int32_t> newChatCountTable;
                for(auto &pair : m_chatCountTable)
                {
                    if(pair.second > 0)
                    {
                        newChatCountTable[pair.first] = pair.second;
                    }
                }
                m_chatCountTable.swap(newChatCountTable);
            }
        }
    }

    PocketSurvival::SubUpdateType SubsystemChatLimit::getUpdateType()
    {
        return PocketSurvival::SubUpdateType::MultiThreadUpdate;
    }

}